<?php
namespace tp5_lib\wxwork\logic;

use think\Db;


/**
 * 获取公司内部通讯录(公司成员、部门)
 * 将数据同步到数据库
 */
class Contact extends WXWork
{
    public function getDepartmentList($id=""){
        $url=$this->host."department/list?access_token=".$this->getToken();
        if($id){
            $url.="&id=".$id;
        }
        $response=$this->get($url);
        return $response["department"];
    }
    //获取简单的用户信息列表
    public function getSimpleUserList($departmentID,$fetchChild=0){
        $url=$this->host."user/simplelist?access_token=".$this->getToken()."&department_id=$departmentID&fetch_child=$fetchChild";
        $response=$this->get($url);
        return $response["userlist"];
    }
    //获取详细的用户信息列表，应用必须有相关权限
    public function getUserList($departmentID,$fetchChild=0){
        $url=$this->host."user/list?access_token=".$this->getToken()."&department_id=$departmentID&fetch_child=$fetchChild";
        $response=$this->get($url);
        return $response["userlist"];
    }
    public function syncData()
    {
        $department=$this->getDepartmentList();
        if(!$department){
            return false;
        }
        $query=Db::table("ww_department");
        $query->execute("TRUNCATE ww_department;");
        $result=$query->insertAll($department);

        $userList=$this->getUserList($department[0]["id"],1);
        if(!$userList){
            return false;
        }
        $map=[];
        foreach($userList as &$user){
            foreach($user["department"] as $index=>$department){
                $map[]=[
                    "userid"=>$user["userid"],
                    "department"=>$department,
                    "order"=>$user["order"][$index]
                ];
            }
            unset($user["extattr"]);
            unset($user["department"]);
            unset($user["order"]);
        }
        $query=Db::table("ww_user");
        $query->execute("TRUNCATE ww_user;");
        $result=$query->insertAll($userList);
        $query=Db::table("ww_user_department");
        $query->execute("TRUNCATE ww_user_department;");
        $result=$query->insertAll($map);
        return $result;
    }
}
